package cn.bkw.ytkapi.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.sql.RowSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

public class JsonObjectUtil {


    public static JSONArray rowSetToJsonArray(RowSet rs) throws SQLException {
        JSONArray jsa = new JSONArray();
        if (rs != null) {
            ResultSetMetaData rsmd = rs.getMetaData();
            while (rs.next()) {
                JSONObject jsobj = new JSONObject();
                for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                    if (rs.getString(rsmd.getColumnName(i)) == null) {
                        jsobj.put(rsmd.getColumnLabel(i), "");
                    } else {
                        jsobj.put(rsmd.getColumnLabel(i), rs.getString(rsmd.getColumnName(i)));
                    }

                }
                jsa.add(jsobj);
            }
        }
        return jsa;
    }

    public static JSONObject rowSetToJsonObject(RowSet rs) throws SQLException {
        JSONObject jsobj = new JSONObject();
        if (rs != null) {
            ResultSetMetaData rsmd = rs.getMetaData();
            if (rs.next()) {
                for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                    if (rs.getString(rsmd.getColumnName(i)) == null) {
                        jsobj.put(rsmd.getColumnLabel(i), "");
                    } else {
                        jsobj.put(rsmd.getColumnLabel(i), rs.getString(rsmd.getColumnName(i)));
                    }
                }
            }
        }
        return jsobj;
    }
}
